package net.jumpengine.event;

import java.util.HashMap;
import java.util.Map;

import javafx.scene.input.MouseButton;
import net.jumpengine.Manager;
import net.jumpengine.bean.ClickBase;
import net.jumpengine.bean.Control;
import net.jumpengine.enume.MouseState;
import net.jumpengine.inter.IControl;
import net.jumpengine.inter.IMouseEvent;

public class MouseMiddle {
	private Map<Enum<?>,IMouseEvent> map=new HashMap<>();
	private IControl focus;
	
	public void click(int x,int y,MouseButton button) {
		IMouseEvent mouseEvent=map.get(Manager.getState());
		if(mouseEvent==null) {
			Manager.getLog().error("MouseMiddle[click] state:", Manager.getState()," mouseEvent为null");
			return;
		}
		ClickBase base = Manager.getEventManager().FindBaseByPoint(x, y,ClickBase.class);
		
		if(base!=null) {
			if(base.isVisible()) {
				if(base instanceof IControl) {
					IControl con=(IControl) base;
					if(con.isAble() && con.getAction()!=null)con.getAction().handle(x, y, button, base);
					mouseEvent.setFocus((IControl) base);
					return;
				}
				base.getAction().handle(x, y, button,base);
			}
		}else {
			mouseEvent.click(x, y,button);
		}
	}
	
	public void move(int x,int y,MouseButton button) {
		IMouseEvent mouseEvent=map.get(Manager.getState());
		if(mouseEvent==null) {
			Manager.getLog().error("MouseMiddle[move] state:", Manager.getState()," mouseEvent为null");
			return;
		}
		
		IControl control = Manager.getEventManager().FindBaseByPoint(x, y,Control.class);
		
		if(control==null) {
			if(focus!=null)focus.setMouseState(MouseState.mouseOut);
			return;
		}
		focus=control;
		mouseEvent.setFocus(control);
		focus.setMouseState(MouseState.mouseIn);
		mouseEvent.mouseMove(x, y,button);
	}
	
	public void pressed(int x, int y, MouseButton button) {
		IMouseEvent mouseEvent=map.get(Manager.getState());
		if(mouseEvent==null) {
			Manager.getLog().error("MouseMiddle[pressed] state:", Manager.getState()," mouseEvent为null");
			return;
		}
		mouseEvent.mousePressed(x, y,button);
	}

	public void released(int x, int y, MouseButton button) {
		IMouseEvent mouseEvent=map.get(Manager.getState());
		if(mouseEvent==null) {
			Manager.getLog().error("MouseMiddle[released] state:", Manager.getState()," mouseEvent为null");
			return;
		}
		mouseEvent.mouseReleased(x, y,button);
	}
	
	public void put(Enum<?> e,IMouseEvent event) {
		map.put(e, event);
	}
	
	public IMouseEvent get(Enum<?> e) {
		return map.get(e);
	}

	public IControl getFocus() {
		return focus;
	}
}
